<template>
  <div class="addSensor">
    <el-dialog class="d1" :title="title" :visible.sync="visible" append-to-body width="90%" @close="onClose">
      <el-form :model="form" ref="form" v-loading="loading" class="form rules" :rules="rules" label-width="140px" size="mini">

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="监测内容：" prop="monitorDetail">
              <el-input v-model.trim="form.monitorDetail" size="small" placeholder="请输入监测内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传感器类型：" prop="sensorType" >
              <el-select class="select1" v-model.trim="form.sensorTypeId" :disabled="form.sensorId==undefined?false:true" @change="handleSensorTypeChange" placeholder="请选择传感器类型" clearable size="small">
                <el-option v-for="dict in selectOptions.typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传感器名称：" prop="device.deviceName">
              <el-input v-model.trim="form.device.deviceName" size="small" placeholder="请输入传感器名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传感器编号：" prop="device.number">
              <el-input v-model.trim="form.device.number" size="small" placeholder="请输入传感器编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="通信设备IMEI：" prop="device.imei">
              <el-input v-model.trim="form.device.imei" size="small" placeholder="请输入IMEI号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传感器描述：" prop="device.description">
              <el-input v-model.trim="form.device.description" size="small" placeholder="请输入传感器描述信息"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商：" prop="device.supplierId">
              <el-select class="select1" v-model.trim="form.device.supplierId" placeholder="请选择供应商" clearable size="small">
                <el-option v-for="dict in selectOptions.supplierOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="点位：" prop="device.pointId">
              <el-select class="select1" v-model.trim="form.device.pointId" placeholder="请选择传感器点位" clearable size="small">
                <el-option v-for="dict in selectOptions.pointOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-row class="row-title" v-if="monitorItems&&monitorItems.length>0">传感器监测项</el-row>
          <template v-for="(monitorItem,i) in monitorItems">
            <el-row :gutter="20" :key="i">
              <el-col :span="3" :offset="1">
                <el-row type="flex">
                  <div>监测项名称：</div>
                  <div>{{monitorItem.itemName}}</div>
                </el-row>
              </el-col>
              <el-col :span="2" >
                <el-row type="flex">
                  <div>单位：</div>
                  <div>{{monitorItem.itemUnit}}</div>
                </el-row>
              </el-col>
              <el-col :span="5" >
                <el-form-item label="1级预警阈值："  :prop="'monitorItems['+i+'].threshold1'" :rules="{required:true,message:'阈值不能输入为空',trigger:'blur'}">
                  <el-input v-model="monitorItem.threshold1" size="small" placeholder="请输入阈值1"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5" >
                <el-form-item label="2级预警阈值："  :prop="'monitorItems['+i+'].threshold2'" :rules="{required:true,message:'阈值不能输入为空',trigger:'blur'}">
                  <el-input v-model="monitorItem.threshold2" size="small" placeholder="请输入阈值2"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5" >
                <el-form-item label="3级预警阈值"  :prop="'monitorItems['+i+'].threshold3'" :rules="{required:true,message:'阈值不能输入为空',trigger:'blur'}">
                  <el-input v-model="monitorItem.threshold3" size="small" placeholder="请输入阈值3"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-row>

        <el-row :gutter="20" v-if="baseParams!=null && baseParams.length!=0">
          <el-row class="row-title">传感器参数</el-row>
          <template v-for="(baseParam,i) in baseParams">
            <el-row :gutter="20" :key="i">
              <el-col :span="3" :offset="1">
                <el-row type="flex">
                  <div>参数名称：</div>
                  <div>{{baseParam.name}}</div>
                </el-row>
              </el-col>
              <el-col :span="2" >
                <el-row type="flex">
                  <div>参数单位：</div>
                  <div>{{baseParam.unit}}</div>
                </el-row>
              </el-col>
              <el-col :span="4" >
                <el-row type="flex">
                  <div>参数说明：</div>
                  <div>{{baseParam.description}}</div>
                </el-row>
              </el-col>
              <el-col :span="5" >
                <el-form-item label="参数值：" prop="threshold">
                  <el-input v-model="baseParams[i].value" size="small" placeholder="请输入参数值"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-row>

        <div class="align-r">
          <el-button size="small" @click="visible=false">取 消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { noRoleListSupplier } from '@/api/slope/supplier';
  import { listSensorType } from "@/api/slope/sensorType";
  import { noRoleListPoint } from "@/api/page/device";
  import { addSensor, updateSensor, checkIMEI } from "@/api/slope/sensor";

  export default {
    props: {
      showBtn: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        loading: false,
        changeImeiValue: null, // 是修改状态时修改imei之前的值
        visible: false,
        title: "",
        defaultForm: {
          sensorTypeId:1,
          device:{
            deviceType:"1",
            isValid:"0",
            state:"1",
            deviceName:"",
            number:"",
            pointId:null,
            supplierId:null,
          },
        },
        form: {
          sensorTypeId:null,
          device:{
            deviceType:"1",
            sensorName:"",
            number:"",
            pointId:null,
            supplierId:null,
            deviceName:""
          }
        },
        monitorItems:[],
        baseParams:[],
        rules: {
          monitorDetail: {required: true,message: "监测内容不能为空"},
          'device.deviceName': {required: true,message: "传感器名称不能为空"},
          'device.number': {required: true,message: "传感器编号不能为空"},
          'device.supplierId': {required: true,message: "供应商不能为空"},
          'device.pointId': {required: true,message: "点位不能为空"},
          'device.imei': [{
            required: true,
            message: "IMEI号不能为空"
          },{
            validator: (rule, value, callback) => {
              if (this.changeImeiValue != value) {
                checkIMEI(value).then(res => {
                  if (res.data.length > 0) {
                    callback('IMEI号重复了');
                  } else {
                    callback()
                  }
                })
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }]
        },
        selectOptions:{
          typeOptions:[],
          pointOptions:[],
          supplierOptions:[]
        },
        sensortTypeList:[]
      };
    },
    created(){
      this.getSensorTypeOptionAndList();
      this.getPointOption();
      this.getSupplierOption();
    },
    methods: {
      onClose() {
        this.form = {
          ...this.defaultForm
        };
      },

      //类型参数
      getSensorTypeOptionAndList(){
        let self=this
        listSensorType().then(response=>{
          self.selectOptions.typeOptions=[];
          for(let i=0;i<response.rows.length;++i){
            let dict={
              dictLabel:response.rows[i].typeName,
              dictValue:response.rows[i].sensorTypeId
            }
            self.selectOptions.typeOptions.push(dict);
          }
          self.sensorTypeList=response.rows;
        })
      },
      //点位下拉列表
      async getPointOption(){
        let self=this
        noRoleListPoint().then(response=>{
          self.selectOptions.pointOptions=[];
          for(let i=0;i<response.rows.length;++i){
            if (response.rows[i].isValid == 1) {
              let dict = {
                dictLabel: response.rows[i].pointName,
                dictValue: response.rows[i].pointId
              }
              self.selectOptions.pointOptions.push(dict);
            }
          }
        })
      },
      //供应商下拉列表
      async getSupplierOption(){
        let self=this
        noRoleListSupplier().then(response=>{
          self.selectOptions.supplierOptions=[];
          for(let i=0;i<response.rows.length;++i){
            if (response.rows[i].isValid!=1){
              let dict={
                dictLabel:response.rows[i].supplierName,
                dictValue:response.rows[i].supplierId
              }
              self.selectOptions.supplierOptions.push(dict);
            }
          }
        })
      },

      async handleClick({ info, title, submit }) {
        let self = this;
        self.form = {
          ...self.defaultForm,
          ...info
        } || {
          ...self.defaultForm
        };

        if(self.form.sensorId==undefined){
          self.handleSensorTypeChange();
        } else{
          self.changeImeiValue = info.device.imei; // 修改时给原先的IMEI赋值

          self.monitorItems=self.form.monitorItems;
          self.baseParams=self.form.baseParams;
        }

        self.title = title || "";
        self.submit = submit || (() => {});
        self.visible = true;
        await self.$nextTick();
        self.$refs["form"].clearValidate();
      },
      async handleSubmit(data) {
        let self = this;
        //对无法绑定的值重新赋值
        self.form.baseParams=self.baseParams;
        self.form.monitorItems=self.monitorItems;

        self.$refs["form"].validate(async valid => {
          if (valid) {
            if (self.form.sensorId != undefined) {
              updateSensor(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("修改成功");
                  self.visible = false;
                  self.$parent.getList();
                } else {
                  self.msgError("修改失败");
                }
              });
            } else {
              addSensor(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("新增成功");
                  self.visible = false;
                  self.$parent.getList();
                } else {
                  self.msgError("新增失败");
                }
              });
            }
          }
        });
      },

      handleSensorTypeChange(){
        let self=this;
        self.monitorItems=[];
        self.baseParams=[];
        for(let i=0;i<self.sensorTypeList.length;++i){
          if(self.sensorTypeList[i].sensorTypeId==self.form.sensorTypeId){
            let sensorType=self.sensorTypeList[i];
            console.log(sensorType);
            //监测项
            if(sensorType.typeItems!=null){
              for(let j=0;j<sensorType.typeItems.length;++j){
                let monitorItem={
                  itemName:sensorType.typeItems[j].name,
                  itemUnit:sensorType.typeItems[j].unit,
                  threshold1:"",
                  threshold2:"",
                  threshold3:""
                }
                self.monitorItems.push(monitorItem);
              }
            }
            //参数
            if(sensorType.typeParams!=null){
              for(let k=0;k<sensorType.typeParams.length;++k){
                let baseParam={
                  name:sensorType.typeParams[k].name,
                  unit:sensorType.typeParams[k].unit,
                  description:sensorType.typeParams[k].description,
                  value:null
                }
                self.baseParams.push(baseParam);
              }
            }
            break;
          }
        }
      }
    }
  };
</script>
<style>
  .row-title{
    margin-bottom: 20px;
    margin-left: 20px;
    font-weight: 600;
  }
</style>
